package com.log;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LogSplitter {
    public static void main(String[] args) {
        String inputFilePath = "C:\\Users\\hcf\\IdeaProjects\\chapter1\\service-hi\\src\\main\\resources\\log.txt";  // 输入日志文件路径
        String outputFilePath = "C:\\Users\\hcf\\IdeaProjects\\chapter1\\service-hi\\src\\main\\resources\\log.txt"; // 输出日志文件路径

        // 定义日志条目开始的正则表达式模式
        Pattern logStartPattern = Pattern.compile("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2} \\[[^\\]]+\\] - \\[[^\\]]+\\] - \\[[^\\]]+\\] - \\[[^\\]]*\\] - \\[[^\\]]+\\] - \\[[^\\]]+\\] - \\[[A-Z]+\\]");

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
             FileWriter writer = new FileWriter(outputFilePath)) {

            String line;
            StringBuilder currentLogEntry = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                Matcher matcher = logStartPattern.matcher(line);
                
                // 如果匹配到日志条目开始，且当前日志条目非空，则写入之前的日志条目并换行
                if (matcher.find() && currentLogEntry.length() > 0) {
                    writer.write(currentLogEntry.toString());
                    writer.write(System.lineSeparator());
                    currentLogEntry.setLength(0);  // 清空 StringBuilder
                }
                
                // 添加当前行到日志条目
                currentLogEntry.append(line).append(System.lineSeparator());
            }
            
            // 写入最后一个日志条目
            if (currentLogEntry.length() > 0) {
                writer.write(currentLogEntry.toString());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
